package com.wyz.saas.common.base

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import com.atom.api.ApiContext
import com.atom.core.AtomApi
import com.atom.module.mvvm.base.AbstractActivity
import com.atom.module.mvvm.base.AbstractBaseViewModel
import com.atom.module.mvvm.base.IViewModel
import com.wyz.saas.api.common.ActivityApi
import com.wyz.saas.common.R
import com.wyz.saas.common.utils.otherwise
import com.wyz.saas.common.utils.yes

abstract class AbstractApiActivity<V : ViewDataBinding, VM : AbstractApiViewModel<*>> :
    AbstractActivity<V, VM>(), ActivityApi {

    private val tag = javaClass.name

    override fun initViewBinding(binding: V?, viewModel: VM?) {
        super.initViewBinding(binding, viewModel)
        viewModel?.also { vm ->
            vm.loadingAction.observe(this, {
                it.value.yes {
                    showLoading()
                }.otherwise {
                    hideLoading()
                }
            })

            vm.finishAction.observe(this, {
                finish()
            })

            vm.onBackPressedAction.observe(this, {
                onBackPressed()
            })

            vm.startActivityAction.observe(this, { pack ->
                val value = pack.value;
                val clz = value[AbstractBaseViewModel.ParameterField.CLASS] as Class<*>?
                val bundle = value[AbstractBaseViewModel.ParameterField.BUNDLE] as Bundle?
                startActivity(clz, bundle)
            })
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return super.onSupportNavigateUp()
    }

    override fun apiContext(): ApiContext {
        return AtomApi.getInstance()
    }

    override fun getActivity(): Activity {
        return this
    }

    protected open fun reportException(ex: Exception) {
        try {
            apiContext().report(tag, ex)
        } catch (e: Exception) {
            ex.printStackTrace()
        }
    }

    open fun exit() {
        super.finish()
    }


    /**
     * 显示错误, 优先使用占位布局
     */
    open fun showError(strRes: Int) {
        showError(resources.getString(strRes))
    }

    @SuppressLint("ShowToast")
    open fun showError(strError: String) {
        apiContext().toast(strError)
    }

    open fun showLoading() {
        apiContext().toast("正在加载...")
    }

    open fun hideLoading() {
        apiContext().toast("加载结束...")
    }

}